<template>
  <el-drawer
    v-model="drawerVisible"
    :title="`${service?.name || '服务'} 日志`"
    size="60%"
    direction="rtl"
  >
    <div class="logs-container">
      <div class="logs-toolbar">
        <div class="logs-filter">
          <el-radio-group v-model="logType" size="small">
            <el-radio-button label="all">全部日志</el-radio-button>
            <el-radio-button label="info">信息</el-radio-button>
            <el-radio-button label="warning">警告</el-radio-button>
            <el-radio-button label="error">错误</el-radio-button>
          </el-radio-group>
        </div>
        <div class="logs-actions">
          <el-button type="primary" size="small" @click="refreshLogs">刷新</el-button>
          <el-button type="default" size="small" @click="exportLogs">导出</el-button>
          <el-button type="danger" size="small" @click="clearLogs">清空</el-button>
        </div>
      </div>
      
      <div class="logs-content" ref="logsContentRef">
        <div v-if="loading" class="logs-loading">
          <el-icon class="rotating">
            <Loading />
          </el-icon>
          <span>加载中...</span>
        </div>
        <div v-else-if="!filteredLogs.length" class="logs-empty">
          <el-empty description="暂无日志数据" />
        </div>
        <div v-else class="logs-list">
          <div 
            v-for="(log, index) in filteredLogs" 
            :key="index" 
            class="log-item"
            :class="{ 
              'log-info': log.type === 'info', 
              'log-warning': log.type === 'warning', 
              'log-error': log.type === 'error' 
            }"
          >
            <div class="log-time">{{ formatTime(log.timestamp) }}</div>
            <div class="log-content">{{ log.content }}</div>
          </div>
        </div>
      </div>
      
      <div class="auto-scroll">
        <el-checkbox v-model="autoScroll">自动滚动至底部</el-checkbox>
      </div>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { Loading } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { type Service } from '../stores/services'

interface LogEntry {
  content: string
  timestamp: number
  type: 'info' | 'warning' | 'error'
}

const props = defineProps<{
  visible: boolean
  service?: Service
}>()

const emit = defineEmits(['update:visible'])

const drawerVisible = ref(props.visible)
const loading = ref(false)
const logs = ref<LogEntry[]>([])
const logType = ref('all')
const autoScroll = ref(true)
const logsContentRef = ref<HTMLElement | null>(null)

watch(() => props.visible, (newValue) => {
  drawerVisible.value = newValue
  if (newValue && props.service) {
    refreshLogs()
  }
})

watch(() => drawerVisible.value, (newValue) => {
  emit('update:visible', newValue)
})

const filteredLogs = computed(() => {
  if (logType.value === 'all') {
    return logs.value
  }
  return logs.value.filter(log => log.type === logType.value)
})

watch(() => filteredLogs.value, () => {
  if (autoScroll.value) {
    scrollToBottom()
  }
}, { flush: 'post' })

const scrollToBottom = () => {
  nextTick(() => {
    if (logsContentRef.value) {
      logsContentRef.value.scrollTop = logsContentRef.value.scrollHeight
    }
  })
}

const refreshLogs = async () => {
  if (!props.service) return
  
  loading.value = true
  
  try {
    // 在实际应用中，这里应该从服务器获取真实的日志数据
    // 模拟异步获取日志数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 生成模拟日志数据
    generateMockLogs()
    
    // 如果自动滚动开启，则滚动到底部
    if (autoScroll.value) {
      scrollToBottom()
    }
  } catch (error) {
    ElMessage.error('获取日志失败')
    console.error('获取日志失败', error)
  } finally {
    loading.value = false
  }
}

const generateMockLogs = () => {
  // 只是模拟生成日志数据，实际项目中应该从服务器获取真实日志
  const mockLogs: LogEntry[] = []
  const logCount = Math.floor(Math.random() * 30) + 20 // 20-50条日志
  const now = Date.now()
  const types: Array<'info' | 'warning' | 'error'> = ['info', 'warning', 'error']
  const serviceActions = [
    '启动服务',
    '停止服务',
    '重启服务',
    '连接成功',
    '连接断开',
    '处理请求',
    '响应请求',
    '配置更新',
    '缓存刷新',
    '资源释放'
  ]
  
  for (let i = 0; i < logCount; i++) {
    const type = types[Math.floor(Math.random() * types.length)]
    const action = serviceActions[Math.floor(Math.random() * serviceActions.length)]
    let content = ''
    
    switch (type) {
      case 'info':
        content = `[INFO] ${action}: 操作成功，服务运行正常。`
        break
      case 'warning':
        content = `[WARN] ${action}: 操作完成，但出现性能下降。`
        break
      case 'error':
        content = `[ERROR] ${action}: 操作失败，服务异常。错误码: E${Math.floor(Math.random() * 1000)}`
        break
    }
    
    mockLogs.push({
      content,
      timestamp: now - (logCount - i) * 60000 - Math.floor(Math.random() * 50000),
      type
    })
  }
  
  logs.value = mockLogs
}

const exportLogs = () => {
  if (!filteredLogs.value.length) {
    ElMessage.warning('没有日志可导出')
    return
  }
  
  const logsText = filteredLogs.value
    .map(log => `[${formatTime(log.timestamp)}] ${log.content}`)
    .join('\n')
  
  const blob = new Blob([logsText], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${props.service?.name || 'service'}-logs-${new Date().toISOString().slice(0, 10)}.log`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  
  ElMessage.success('日志导出成功')
}

const clearLogs = () => {
  logs.value = []
  ElMessage.success('日志已清空')
}

const formatTime = (timestamp: number) => {
  const date = new Date(timestamp)
  return date.toLocaleString()
}

onMounted(() => {
  if (props.visible && props.service) {
    refreshLogs()
  }
})

defineExpose({
  drawerVisible,
  refreshLogs
})
</script>

<style scoped>
.logs-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0 20px;
}

.logs-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.logs-content {
  flex-grow: 1;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f5f7fa;
  padding: 10px;
  height: calc(100vh - 250px);
}

.logs-loading {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
}

.logs-empty {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.logs-list {
  font-family: monospace;
  font-size: 14px;
}

.log-item {
  display: flex;
  margin-bottom: 5px;
  padding: 5px;
  border-radius: 3px;
}

.log-info {
  background-color: #ecf5ff;
  color: #409EFF;
}

.log-warning {
  background-color: #fdf6ec;
  color: #E6A23C;
}

.log-error {
  background-color: #fef0f0;
  color: #F56C6C;
}

.log-time {
  flex-shrink: 0;
  width: 180px;
  margin-right: 10px;
  font-weight: bold;
}

.log-content {
  flex-grow: 1;
  word-break: break-all;
}

.auto-scroll {
  margin-top: 10px;
  text-align: right;
}

.rotating {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style> 